#include "MainWindow.h"

MainWindow::MainWindow() {
    // 设置中文字体
    QFont font;
    font.setFamily("Microsoft YaHei");  // 设置字体为微软雅黑
    font.setPointSize(12);              // 设置字体大小

    // 应用字体到所有子控件
    this->setFont(font);

    setWindowTitle("智能停车");
    setFixedSize(800, 600);
    date = new SaveDate("QSQLITE");
    date->InitDate(&plates);

    QWidget* widget = new QWidget;
    auto* layout = new QVBoxLayout(widget);
    view = new QTableView(widget);
    view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    auto* in_btn1 = new QPushButton("Enter1", widget);
    in_btn1->setFixedHeight(20);
    auto* out_btn1 = new QPushButton("Exit1", widget);
    out_btn1->setFixedHeight(20);
    auto* in_btn2 = new QPushButton("Enter2", widget);
    in_btn2->setFixedHeight(20);
    auto* out_btn2 = new QPushButton("Exit2", widget);

    auto* btn_layout = new QVBoxLayout;
    btn_layout->addWidget(in_btn1, 1);
    btn_layout->addWidget(out_btn1, 1);
    btn_layout->addWidget(in_btn2, 1);
    btn_layout->addWidget(out_btn2, 1);

    timeLabel = new QLabel;
    timeLabel->setFixedHeight(60);
    timeLabel->setText(QDateTime::currentDateTime().toString("yyyy-M-dd HH:mm:ss"));  // 初始时间
    timeLabel->setStyleSheet(
        "QLabel { color: black; background-color: white;"
        "font-weight: bold; font-size: 48px; }");
    timeLabel->setAlignment(Qt::AlignCenter);

    // 创建定时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this,
            &MainWindow::updateTime);
    timer->start(1000);  // 每秒更新一次

    txtLabel = new QLabel;
    txtLabel->setFixedSize(500, 100);

    auto* frame = new QFrame(widget);
    frame->setFrameShape(QFrame::VLine);
    frame->setFrameShadow(QFrame::Sunken);

    auto* hlayout = new QHBoxLayout;
    hlayout->addLayout(btn_layout);
    hlayout->addWidget(frame);
    hlayout->addWidget(txtLabel);

    frame->setFrameShape(QFrame::HLine);
    // 设置比例
    layout->addLayout(hlayout, 2);
    layout->addWidget(frame);
    layout->addWidget(timeLabel);
    layout->addWidget(frame);
    layout->addWidget(view, 6);

    // 设置布局
    setCentralWidget(widget);

    connect(in_btn1, &QPushButton::clicked, this,
            &MainWindow::EnterBtn);
    connect(in_btn2, &QPushButton::clicked, this,
            &MainWindow::EnterBtn);
    connect(out_btn1, &QPushButton::clicked, this,
            &MainWindow::ExitBtn);
    connect(out_btn2, &QPushButton::clicked, this,
            &MainWindow::ExitBtn);

    connect(view, SIGNAL(clicked(const QModelIndex&)), this,
            SLOT(onTableClicked(const QModelIndex&)));

    showView();
}

MainWindow::~MainWindow() {
    delete date;
}

QString MainWindow::deqStr(QString& qstr) {
    QString res;

    int start = qstr.lastIndexOf('/');
    int end = qstr.indexOf('.');

    res = qstr.mid(start + 1, end - start - 1);

    return res;
}

std::string MainWindow::deStr(std::string& str) {
    QString res;

    QString qstr = QString(str.c_str());

    int start = qstr.lastIndexOf('/');
    int end = qstr.indexOf('.');

    res = qstr.mid(start + 1, end - start - 1);

    return res.toStdString();
}

void MainWindow::showView() {
    QSqlQueryModel* model = date->GetModel();
    view->setModel(model);
}

void MainWindow::ExitBtn() {
    QString imagepath = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "", tr("Images (*.png *.jpg *.jpeg *.gif *.bmp)"));

    if (!imagepath.isEmpty()) {
        // 处理传入图片
        plate_image.editImage(imagepath);

        std::string str = plate_image.getImageName();

        if (!str.empty() && plates.find_plate(str)) {
            // 计算停车时间，计费
            Info* temp = plates.pop_plate(str);
            date->DeletePlate(str);
            if (temp) {
                temp->out_time = Plates::getCurrentTime();
                quint64 endtime = QDateTime::currentDateTime().toSecsSinceEpoch();

                quint64 seconds = endtime - temp->starttime;

                // qDebug() << "now: " << endtime << " start: " << temp->starttime;
                // qDebug() << "sec: " << seconds;
                double hours = static_cast<double>(seconds) / SECONDS_OF_HOUR;

                QString qstr = QString(temp->name.c_str()) + "\n" + temp->in_time +
                               " Enter garage\n" + temp->in_time + " Exit sucess\n" +
                               "total time: " + QString::number(hours) + "h     expense: " +
                               QString::number(500 * hours) + "元";
                txtLabel->setText(qstr);
                // 释放Info
                delete temp;
            } else {
                txtLabel->setText("The plate fatal");
            }
        } else {
            txtLabel->setText("The car is not in storage");
        }
        showView();
    }
}

void MainWindow::updateTime() {
    QDateTime currentTime = QDateTime::currentDateTime();
    QString timeString = currentTime.toString("yyyy-M-dd HH:mm:ss");
    timeLabel->setText(timeString);
}

void MainWindow::onTableClicked(const QModelIndex& index) {
    if (index.isValid()) {
        std::string place = index.data().toString().toStdString();

        if (place.length() == 16) {
            QImage image = plates[place]->image;

            ImageDialog dialog(image);
            dialog.resize(600, 400);
            dialog.exec();  // 显示图片
        }
    }
}

void MainWindow::EnterBtn() {
    QString imagepath = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "", tr("Images (*.png *.jpg *.jpeg *.gif *.bmp)"));
    if (!imagepath.isEmpty()) {
        // 处理传入图片
        plate_image.editImage(imagepath);

        std::string temp = plate_image.getImageName();
        if (temp.empty() && temp.size() != 16) {
            qDebug() << "plateRecognize error";
            return;
        }
        if (plates.find_plate(temp)) {
            txtLabel->setText("The car is already in the garage");
            return;
        }
        // qDebug() << temp.c_str() << " " << temp.length();

        auto* info = new Info;
        info->name = temp;
        qDebug() << "plate: " << info->name.c_str();

        info->starttime = QDateTime::currentDateTime().toSecsSinceEpoch();
        info->in_time = Plates::getCurrentTime();
        info->image = QImage(imagepath);
        plates.push_plate(info);
        date->InsertPlate(info);

        txtLabel->setText(QString::fromStdString(temp) + " Enter the garage");
        // txtLabel->setText(QString::fromWCharArray(L"中文乱码") + " Enter the garage");
        // txtLabel->setText(QString::fromLocal8Bit("中文乱码") + " Enter the garage");
        // txtLabel->setText(QStringLiteral("中文乱码") + " Enter the garage");
    } else {
        txtLabel->setText("No car are coming in");
    }
    showView();
}
